import java.util.Collection;

import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ChatManager;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.RosterEntry;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Presence;

import java.lang.*;
import java.io.*;
import java.lang.String;
import java.net.*;
import java.security.*;
import java.awt.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Properties;

import javax.swing.event.ListDataListener;

public class Main implements MessageListener, ActionListener{
	String message,to;
	Chat chat;
	static ConnectionConfiguration config;
	static XMPPConnection connection;
	Roster roster;
	Collection<RosterEntry> entries;
	ChatManager chatmanager;
	
	GiveReply gr = new GiveReply();
	
    String line = "", key = "";
    static DataInputStream in;
    static PrintStream out;
    static BufferedReader ink;
    static Thread thread;
    static Runnable runnable;
    static JTextField tfLogin;
    static JPasswordField tfPasswd;
    static AbstractButton button;
    static JFrame f, f1;

    static JPanel jp;
    DefaultListModel list1Model;
    JList list1;

    private Message msg;
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		config = 
			new ConnectionConfiguration("talk.google.com", 
							5222, 
							"gmail.com");
		connection = new XMPPConnection(config);
		tfLogin = new JTextField(10);
		tfLogin.setText("");
		tfLogin.setPreferredSize(tfLogin.getPreferredSize());
		tfPasswd = new JPasswordField(10);
		tfPasswd.setPreferredSize(tfPasswd.getPreferredSize());
		tfPasswd.setText("");
		
		

		JPanel pLogin = new JPanel();
		pLogin.setBorder(new javax.swing.border.TitledBorder("Login-ID:"));
		pLogin.add(tfLogin);

		JPanel pPasswd = new JPanel();
		pPasswd.setBorder(new javax.swing.border.TitledBorder("Password:"));
		pPasswd.add(tfPasswd);

		f = new JFrame("UNICORN");
		f.setSize(200, 250);
		f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		f.getContentPane().setLayout(new java.awt.GridLayout(3, 0));
		f.getContentPane().add(pLogin);
		f.getContentPane().add(pPasswd);
		Container content = f.getContentPane();
		content.setBackground(Color.white);
		content.setLayout(new FlowLayout());
		button = new JButton("go!");
		button.addActionListener(new Main());
		content.add(button);
		//f.addWindowListener(new ExitListener());
		f.setVisible(true);
		

	}

	@Override
	public void processMessage(Chat chat, Message message) {
		// TODO Auto-generated method stub
	String temp,reply="";
	boolean recog=false;
	temp="";
	msg=new Message();

	if(message.getBody() != null) {  
            temp=message.getBody();
            System.out.println("Received: " + temp + " from "+message.getFrom());
            try {
            	reply=gr.response(temp);
            	if(reply.length()==0)
            	{
            		reply=gr.randomResponse();
            		System.out.println("random reponse = "+reply);
            	}
            	
            		msg.setBody(reply);
                chat.sendMessage(msg);
            } catch (XMPPException ex) {
                //ex.printStackTrace();
                System.out.println("Failed to send message");
            }
        } 

		
	}
	

	@Override
	public void actionPerformed(ActionEvent e) {
		boolean pass=true;
		
		// TODO Auto-generated method stub
		if ((e.getActionCommand()).equals("go!")) {
			System.out.println("go pressed");
			try {
			//System.out.println("content of password field is in between:"+tfPasswd.getText()+":");
				
				if(tfPasswd.getText().equals("")){
					System.out.println("password field was empty");
					if(Encryption.getPassword(tfLogin.getText()).equals("")){
						System.out.println("could not retrieve password");
						pass=false;
					}
					else{
							System.out.println("could retrieve password");
							tfPasswd.setText(Encryption.getPassword(tfLogin.getText()));
					}
				}
				
				
				if(pass==true)
				{
				connection.connect();
				connection.login(tfLogin.getText()+"@gmail.com", tfPasswd.getText());
				System.out.println("Login Done");
				Encryption.storePassword(tfLogin.getText(),tfPasswd.getText() );
				Presence presence = new Presence(Presence.Type.available);
	            connection.sendPacket(presence);

				roster = connection.getRoster();
				entries = roster.getEntries();
				 
				
				f.setVisible(false);
                f1 = new JFrame("UNICORN");
                f1.setSize(300, 500);
                f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

                initUI();

                f1.getContentPane().add(jp);

                f1.setVisible(true);
                
                chatmanager = connection.getChatManager();
                for(RosterEntry r:entries)
        		{
        			//System.out.println(r.getType() +" : "+r.getUser() );
        			//list1Model.addElement(r.getUser());
        			chatmanager.createChat(r.getUser().toString(), this);
        			
        		}
			}

			} catch (XMPPException e1) {
				System.out.println();
				e1.printStackTrace();
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			
		}
		
	}

	private void initUI() throws IOException {
		// TODO Auto-generated method stub

        jp = new JPanel();
       

        list1Model = new DefaultListModel();
        for(RosterEntry r:entries)
		{
			System.out.println(r.getType() +" : "+r.getUser() );
			list1Model.addElement(r.getUser());
			//chatmanager.createChat(r.getUser(), this);
			
		}
        list1 = new JList(list1Model);
        
        JScrollPane sp1 = new JScrollPane(list1);
        sp1.setBorder(BorderFactory.createLineBorder(Color.BLACK, 1));

        jp.setLayout(new java.awt.GridLayout(1, 0));
        jp.add(sp1);

	}

}
